package com.example.myapplication

import android.animation.ValueAnimator
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.ScrollView
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.lifecycle.lifecycleScope
import com.google.android.material.floatingactionbutton.FloatingActionButton
import kotlinx.coroutines.Job
import kotlinx.coroutines.delay
import kotlinx.coroutines.launch

class scrollview : AppCompatActivity() {
    
    private lateinit var scrollView: ScrollView
    private lateinit var fabBackToTop: FloatingActionButton
    private var scrollJob: Job? = null
    private val scrollThreshold = 300 // 300dp threshold
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_scrollview)
        
        // 初始化视图
        initViews()
        
        // 设置滚动监听
        setupScrollListener()
        
        // 设置按钮点击事件
        setupFabClickListener()
        
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }
        
        // 测试按钮是否正确初始化
        Log.d("ScrollView", "FAB initialized: ${::fabBackToTop.isInitialized}")
    }
    
    private fun initViews() {
        scrollView = findViewById(R.id.scrollView)
        fabBackToTop = findViewById(R.id.fabBackToTop)
        
        // 确保按钮初始状态正确
        fabBackToTop.visibility = View.GONE
        fabBackToTop.alpha = 0f
    }
    
    private fun setupScrollListener() {
        // 使用ViewTreeObserver监听滚动变化
        scrollView.viewTreeObserver.addOnScrollChangedListener {
            val scrollY = scrollView.scrollY
            val threshold = (scrollThreshold * resources.displayMetrics.density).toInt()
            
            Log.d("ScrollView", "ScrollY: $scrollY, Threshold: $threshold")
            
            // 取消之前的协程任务
            scrollJob?.cancel()
            
            // 启动新的协程处理滚动事件
            scrollJob = lifecycleScope.launch {
                // 添加小延迟以避免频繁触发
                delay(50)
                
                if (scrollY > threshold) {
                    showFabWithAnimation()
                } else {
                    hideFabWithAnimation()
                }
            }
        }
    }
    
    private fun setupFabClickListener() {
        fabBackToTop.setOnClickListener {
            Log.d("ScrollView", "FAB clicked")
            smoothScrollToTop()
        }
    }
    
    private fun showFabWithAnimation() {
        runOnUiThread {
            if (fabBackToTop.visibility != View.VISIBLE) {
                Log.d("ScrollView", "Showing FAB")
                fabBackToTop.visibility = View.VISIBLE
                fabBackToTop.animate()
                    .alpha(1f)
                    .setDuration(200)
                    .start()
            }
        }
    }
    
    private fun hideFabWithAnimation() {
        runOnUiThread {
            if (fabBackToTop.visibility == View.VISIBLE) {
                Log.d("ScrollView", "Hiding FAB")
                fabBackToTop.animate()
                    .alpha(0f)
                    .setDuration(200)
                    .withEndAction {
                        fabBackToTop.visibility = View.GONE
                    }
                    .start()
            }
        }
    }
    
    private fun smoothScrollToTop() {
        val currentScrollY = scrollView.scrollY
        Log.d("ScrollView", "Smooth scroll from: $currentScrollY to 0")
        
        val animator = ValueAnimator.ofInt(currentScrollY, 0)
        animator.duration = 500
        animator.interpolator = android.view.animation.DecelerateInterpolator()
        
        animator.addUpdateListener { animation ->
            val animatedValue = animation.animatedValue as Int
            scrollView.scrollTo(0, animatedValue)
        }
        
        animator.start()
    }
    
    override fun onDestroy() {
        super.onDestroy()
        // 取消协程任务以避免内存泄漏
        scrollJob?.cancel()
    }
}